package com.houguanghui.examples.netty.quickstart;

import java.nio.charset.StandardCharsets;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class HelloWordServerHandler extends ChannelInboundHandlerAdapter {

  @Override
  public void channelActive(final ChannelHandlerContext ctx) {
    final String message = "Hello World\n";
    final ByteBuf buffer = ctx.alloc().buffer();
    buffer.writeBytes(message.getBytes(StandardCharsets.UTF_8));

    final ChannelFuture f = ctx.writeAndFlush(buffer);
    f.addListener(ChannelFutureListener.CLOSE);
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    cause.printStackTrace();
    ctx.close();
  }
}